var objA01_TT88HK = [];
var objA01_G32LK9 = [];
var objA01_LKL787 = [];
var objA01_G6HHK8 = [];
var objA01_T881NV = [];
var selInfRow = null;
var param_name =  'A01_TT88HK';
var param_name2 = 'A01_G32LK9';
var param_name3 = 'A01_LKL787';
var param_name4 = 'A01_T89K7A';
var param_name5 = "A01_G6HHK8";
var param_name6 = "A01_T881NV";
var ly_index;

var columns = [{
    field: 'checked',
    checkbox: true,
    width: '50px'
},
{
    title: '主键',
    field: 'MAIN_ID',
    sortable: true,
    visible: false
},
{
    title: '模板名',
    field: 'TAG_NAME',
    sortable: true,
    width: '120px'
},
{
    title: '模板效果图',
    field: 'TAG_IMG',
    sortable: true,
    width: '300px',
    formatter: function(value, row, index) {
        if (value != null) {
            return "<img src='" + imgUrl + value + "' width='285px'/>";
        } else {
            return value;
        }
    }
},
{
    title: '模板代码',
    field: 'TAG_INFO',
    sortable: true,
    width: '150px',
    formatter: function(value, row, index) {
        value = s_decode(value);
        if (value != "" && value != null && value != undefined) {
            value = value.replace(/[<]/g, "&lt;").replace(/[>]/g, "&gt;").replace(/\r\n/g, "").replace(/\n/g, "").replace(/[\"]/g, "&quot;").replace(/[\']/g, "&apos;").replace(/[\r\n]/g, '<br>'); // .replace(/\s/g,"")
        }
        return value;
    }
},
{
    title: '模板中文名',
    field: 'S_DESC',
    sortable: true,
    width: '100px'
},
{
    title: '关联接口',
    field: 'PROC_ID',
    sortable: true,
    width: '250px',
    formatter: function(value, row, index) {
        let html_select_head = "<select style='width:235px;' id='" + param_name + "_" + row.MAIN_ID + "' onchange='selectA01_TT88HK(this)'>";
        let html_select_content = "<option value=''></option>";
        let html_select_foot = "</select>";
        $.each(objA01_LKL787,
        function(i, obj) {
            let html_option = "<option value='" + obj.MAIN_ID + "'>" + obj.INF_CN_NAME + "[" + obj.INF_EN_NAME + "]" + "</option>";
            html_select_content = html_select_content + html_option;
        });
        value = html_select_head + html_select_content + html_select_foot;
        return value;
    }
},
{
    title: '要素关联',
    field: 'TAG_COLUMN',
    sortable: true,
    width: '300px',
    formatter: function(value, row, index) {
        let html_head = "<table id='tbColumn_" + row.MAIN_ID.toString() + "'>" + "<tr>" + "<th>要素值</th><th>要素描述</th><th>返回值</th><th>要素ID</th>" + "</tr>";
        let html_content = "";
        let html_foot = "</table>";
        let MAIN_ID = row.MAIN_ID;
        $.each(objA01_G32LK9,function(i, obj) {
            if (MAIN_ID == obj.MAIN_ID) {
                let html_tr = "<tr>" + "<td>" + obj.TAG_VALUE + "</td><td>" + obj.TAG_DESC + "</td><td><select style='width:100px;' id='" + param_name2 + "_" + obj.TAG_COLUMN_ID + "'></select></td><td>" + obj.TAG_COLUMN_ID + "</td>" + "</tr>";
                html_content = html_content + html_tr;
            }
        });
        value = html_head + html_content + html_foot;
        return value;
    }
},
{
    title: '跳转页面&选择嵌套父级外键',
    field: 'PROC_ID',
    sortable: true,
    width: '250px',
    formatter: function(value, row, index) {
        let html_select_head = "跳转页面：<select style='width:240px;' id='url_" + param_name + "_" + row.MAIN_ID + "'>";
        let html_select_content = "<option value=''></option>";
        let html_select_foot = "</select>";
        $.each(objA01_G6HHK8,function(i, obj) {
            let html_option = "<option value='" + obj.MAIN_ID + "'>" + obj.MENU_NAME + "[" + s_decode(obj.MENU_URL) + "]" + "</option>";
            html_select_content = html_select_content + html_option;
        });
        value = html_select_head + html_select_content + html_select_foot;
        
        let html_select_head_sub = "选择嵌套父级外键：<select style='width:240px;' id='sub_" + param_name + "_" + row.MAIN_ID + "'>";
        let html_select_content_sub = "<option value=''></option>";
        let html_select_foot_sub = "</select>";
        value += html_select_head_sub + html_select_content_sub + html_select_foot_sub;
        
        return value;
    }
}];


function selectAPP_FRAME(obj){
	var curWwwPath=window.document.location.href;
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    var localhostPath=curWwwPath.substring(0,pos);
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
	
	$("#h5_url").attr("href",localhostPath+"/"+projectName+"/cdi_app"+$(obj).val()+"/main/login.html");
	$('#appTagTable').bootstrapTable("removeAll");
    let objU = baseUrl + "&param_name=" + param_name+"&param_value1="+$(obj).val();
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
        	objA01_TT88HK = datas[param_name];
            initTable();
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });	
}

function selectA01_TT88HK(obj) {
    selInfRow = obj.parentElement.parentElement;
    let A01_TT88HK_main_id = obj.id.replace("A01_TT88HK_", "");
    if(A01_TT88HK_main_id.indexOf("_") != -1)
    	A01_TT88HK_main_id = A01_TT88HK_main_id.split("_")[0]
    let proc_id = obj.value;
    let proc_name = $(obj).find("option:selected").text();
    let objU = baseUrl + "&param_name=" + param_name4 + "&param_value1=" + proc_id;
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
        	let data4 = datas[param_name4];
            let html_select_content = "<option value=''></option>";
            var subSelects = $(selInfRow).find("td:eq(6) select");            
            $.each(data4, function(i, obj) {
                let html_option = "<option value='" + obj.MAIN_ID + "'>" + obj.RETURN_NAME + "</option>";
                html_select_content = html_select_content + html_option;
            });
            $($(selInfRow).find("td:eq(-1) select")[1]).html(html_select_content);
            $.each(objA01_G32LK9, function(i, obj) {
                if (A01_TT88HK_main_id == obj.MAIN_ID) {
                	$.each(subSelects,function(n,tagOb){
                		$(tagOb).html(html_select_content);
                	});
                }
            });
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

function initTable() {
    $('#appTagTable').bootstrapTable('destroy');
    $("#appTagTable").bootstrapTable({
        uniqueId: 'MAIN_ID',
        search: !0,
        pagination: !0,
        showRefresh: !0,
        showToggle: !0,
        showColumns: !0,
        iconSize: "outline",
        onClickRow: function(row, $element) {
            // 判断是否已选中
            if ($($element).hasClass("changeColor")) {
                // 已选中则移除 当前行的class='changeColor'
                // $($element).removeClass('changeColor');
                $('#appTagTable').find("tr.changeColor").removeClass('changeColor');
                selectRowId = "";
            }　　　　　　
            else {
                // 未点击则，为当前行添加 class='changeColor'
                $('#appTagTable').find("tr.changeColor").removeClass('changeColor');
                $($element).addClass('changeColor');　selectRowId = $element.attr('data-index');
            }
        },
        toolbar: "#appTagTableToolbar",
        columns: columns,
        data: objA01_TT88HK,
        pageNumber: 1,
        pageSize: 2000,
        // 每页的记录行数（*）
        pageList: [2000, 2100, 2200, 2300],
        // 可供选择的每页的行数（*）
        icons: {
            refresh: "glyphicon-repeat",
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list"
        }
    });
}

function set_A01_TT88HK() {
    $('#appTagTable').bootstrapTable("removeAll");
    let objU = baseUrl + "&param_name=" + param_name+"&param_value1=1";
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
        	objA01_TT88HK = datas[param_name];
            set_A01_G6HHK8();
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

function set_A01_G6HHK8(){
	$('#appTagTable').bootstrapTable("removeAll");
    let objU = baseUrl + "&param_name=" + param_name5;
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
            objA01_G6HHK8 = datas[param_name5];
            set_A01_T881NV();
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

function set_A01_T881NV(){
	$('#appTagTable').bootstrapTable("removeAll");
    let objU = baseUrl + "&param_name=" + param_name6;
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
        	objA01_T881NV = datas[param_name6];            
            $.each(objA01_T881NV, function(i, obj) {
        		var objDev = "<option value=\""+obj.MAIN_ID+"\">"+obj.FRAME_NAME+"</>";
        		$("#SEL_APP_FRAME").append(objDev);
            });
            set_A01_NNNVVV();
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

function set_A01_NNNVVV(){
	let objU = baseUrl + "&param_name=A01_NNNVVV";
	ly_index = layer.load();
	$.ajax({
	    type: 'POST',
	    url: objU,
	    dataType: 'json',
	    success: function(datas) { // 返回list数据并循环获取
	    	layer.close(ly_index);
	    	$("#SEL_APP_USER_ZXY").append("<option value=\"-1\"></>");
	    	$.each(datas.A01_NNNVVV, function(i, obj) {
	    		var objDev = "<option value=\""+obj.MAIN_ID+"\">"+obj.PAGE_TITLE+"</>";
	    		$("#SEL_APP_USER_ZXY").append(objDev);
	        });
	    	initTable();
	    },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
	});
}

function set_A01_G32LK9() {
    let objU = baseUrl + "&param_name=" + param_name2;
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
        	objA01_G32LK9 = datas[param_name2];
            set_A01_TT88HK();
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

function get_A01_LKL787() {
    let objU = baseUrl + "&param_name=" + param_name3;
    ly_index = layer.load();
    $.ajax({
        type: 'POST',
        url: objU,
        dataType: 'json',
        success: function(datas) { // 返回list数据并循环获取
        	layer.close(ly_index);
        	objA01_LKL787 = datas[param_name3];
            set_A01_G32LK9();
        },
        error: function () {
            layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
                function () {
                window.location.reload();
            })
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function (XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

var jIndex = "";

function AddS1(inputData) {
    if (jIndex == "") {
        var s = (parseInt("1" + inputData) + 1).toString().substring(1, 4);
        return s;
    } else {
        var s = (parseInt("1" + jIndex) + 1).toString().substring(1, 4);
        return s;
    }
}

$("#btn_copy").click(function() {
    var selData = $("#appTagTable").bootstrapTable('getSelections');
    if (selData.length <= 0) {
        alert("请选中一行")
    } else {
        $.each(selData,function(i, obj) {
            var newTR = $("#A01_TT88HK_" + obj.MAIN_ID.toString()).parent().parent();
            var trHtml = $(newTR[0]).prop("outerHTML");
            var objTR = $(trHtml);
            // 修改第2列中信息
            var td1_html = objTR.find("td:eq(1)").html();
            jIndex = AddS1(td1_html.substring(7, 10));
            var td1_text = td1_html.substring(0, 7) + jIndex + "_template";
            objTR.find("td:eq(1)").html(td1_text);

            // 修改第6列中信息
            var td5_select = objTR.find("td:eq(5)").find("select");
            td5_select.attr("id", td5_select.attr("id") + "_" + parseInt(jIndex));

            $("#appTagTable").find($(newTR)).after(objTR);
        });
    }
});

// app项目打包下载
$('#btn_downproj').click(function(){
	ly_index = layer.load();
	$.ajax({
        type: "POST",
        async: false,
        url: baseUrl,
        data: {
            param_name: "A01_CCC888",
            session_id: session_id,
            param_value1: $("#SEL_APP_FRAME").val()
        },
        // 跨域请求的URL
        dataType: "jsonp",
        jsonp: "jsoncallback",
        success: function(data) {
        	layer.close(ly_index);
        	$("#proj_url").text(data.A01_CCC888[0].biz_name);
     	    $("#proj_url").attr("href", basePath+"/"+contextPath+"/"+data.A01_CCC888[0].biz_url);
     	    swal({
     	        title: "提醒",
     	        text: "h5项目打包成功！",
     	        type: "success",
     	        confirmButtonColor: "#DD6B55",
     	        confirmButtonText: "确定"
     	    });
        },
        error: function() {
        	layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
            function() {
                window.location.reload();
            });
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function(XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
});

$('#btn_set').click(function() {
	
	var selData = $('input:checkbox[name=btSelectItem]:checked');
	if (selData.length <= 0) {
        alert("请选中一行")
    } else {
        // var strSelData = JSON.stringify(selData);
        // 模板ID
        var selMain_ID = "";
        // 接口ID
        var PorcMAIN_ID = "";
        // 获取标签column ID
        var tagColumnID = "";
        // 获取接口返回值ID
        var ProcReturnID = "";
        // 获取模板名称
        var templateName = "";
        // 获取跳转页面ID
        var urlPathID = "";
        // 获取嵌套父级外键
        var P_MAIN_ID = "";
        
        $.each(selData,function(i, obj) {
        	var temTR = $(obj.parentElement.parentElement);
            if (i == 0) {
                selMain_ID = temTR.attr("data-uniqueid");
                PorcMAIN_ID = temTR.find("td:eq(5)").find("select").val();
                templateName = temTR.find("td:eq(1)").html();
                urlPathID = $(temTR.find("td:eq(-1)").find("select")[0]).val();
                P_MAIN_ID = $(temTR.find("td:eq(-1)").find("select")[1]).val();
            } else {
                selMain_ID += "," + temTR.attr("data-uniqueid");
                PorcMAIN_ID += "," + temTR.find("td:eq(5)").find("select").val();
                templateName += ","+temTR.find("td:eq(1)").html();
                urlPathID += ","+$(temTR.find("td:eq(-1)").find("select")[0]).val();
                P_MAIN_ID += ","+$(temTR.find("td:eq(-1)").find("select")[1]).val();
                tagColumnID += ",";
                ProcReturnID += ",";
            }

            var trs = temTR.find("td:eq(6)").find("table").find("tr");
            
            $.each(trs,function(j, objTD) {
                if (j > 0) {
                    if (j == 1) {
                        tagColumnID += $(trs[j]).find("td:eq(3)").text();
                        var temSel = $(trs[j]).find("td:eq(2)").find("select").val();
                        if (temSel == "") temSel = "-1";
                        ProcReturnID += temSel;
                    } else {
                        tagColumnID += "|" + $(trs[j]).find("td:eq(3)").text();
                        var temSel = $(trs[j]).find("td:eq(2)").find("select").val();
                        if (temSel == "") temSel = "-1";
                        ProcReturnID += "|" + temSel;
                    }
                }
            });
        });

        set_A01_TTT999(selMain_ID, PorcMAIN_ID, tagColumnID, ProcReturnID,templateName,urlPathID,P_MAIN_ID);
    }
});

function A01_TTT999(input) {
    var data = input.A01_TTT999;
    var s_result = "0";
	var error_desc = "";
	for (var key in data[0]) {
		if (key == 's_result')
		{
			s_result = data[0].s_result;
			error_desc = data[0].error_desc;
		}
	}
	if (s_result == "0") {
		swal("生成代码失败！", "生成代码失败！:"+error_desc, "warning");
	}
	else
	{
	    $("#biz_url").text(data[0].biz_name);
	    $("#biz_url").attr("href", fileUrl+"/"+data[0].biz_url);
	    swal({
	        title: "提醒",
	        text: "生成代码成功！",
	        type: "success",
	        confirmButtonColor: "#DD6B55",
	        confirmButtonText: "确定"
	    });
	}
}

function set_A01_TTT999(selMain_ID, PorcMAIN_ID, tagColumnID, ProcReturnID,templateName,urlPathID,P_MAIN_ID) {
	ly_index = layer.load();
	$.ajax({
        type: "POST",
        async: false,
        url: baseUrl,
        data: {
            param_name: "A01_TTT999",
            session_id: session_id,
            param_value1: selMain_ID,
            param_value2: PorcMAIN_ID,
            param_value3: tagColumnID,
            param_value4: ProcReturnID,
            param_value5: templateName,
            param_value6: $("#biz_name").val(),
            param_value7: $("#SEL_APP_USER_ZXY").val(),
            param_value8: urlPathID,
            param_value9: $("#SEL_APP_FRAME").val(),
            param_value10:P_MAIN_ID
        },
        // 跨域请求的URL
        dataType: "jsonp",
        jsonp: "jsoncallback",
        jsonpCallback: "A01_TTT999",
        success: function() {
        	layer.close(ly_index);
        },
        error: function() {
        	layer.close(ly_index);
            swal({
                title: "告警",
                text: "网络异常或系统故障，请刷新页面！",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "刷新",
                closeOnConfirm: false
            },
            function() {
                window.location.reload();
            });
        },
        // 请求完成后的回调函数 (请求成功或失败之后均调用)
        complete: function(XMLHttpRequest, textStatus) {
            $("#doing").empty();
            $("#doing").attr("style", "display:none");
        }
    });
}

$(document).ready(function() {
    get_A01_LKL787();
    $("#proj_url").attr("href", basePath+contextPath+"/cdi_app1.rar");   
});